package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.app.func.DimAsyncFunction;
import com.atguigu.education.bean.TradeGMVBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @title: DwsTradetotalOrderWindow
 * @Author Mr.Liu
 * @Date: 2022/9/4 9:13
 * @Version 1.0
 */
public class DwsTradetotalOrderWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */
        String orTopic = "dwd_trade_order_pre_process";
        String uqTopic = "dwd_trade_unique_buyer_detail1";
        String groupID = "dws_trade_total_order_window";
        DataStreamSource<String> orderSource = env.addSource(KafkaUtil.getKafkaConsumer(orTopic,groupID+"111" ));
        DataStreamSource<String> uniqueSource = env.addSource(KafkaUtil.getKafkaConsumer(uqTopic, groupID+"121"));

        //order
        SingleOutputStreamOperator<JSONObject> jsonStream = orderSource.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String s) throws Exception {
                return JSONObject.parseObject(s);
            }
        });
        //订单数
        SingleOutputStreamOperator<TradeGMVBean> orderCountStream = jsonStream.keyBy(s -> s.getString("order_id")).map(new MapFunction<JSONObject, TradeGMVBean>() {
            @Override
            public TradeGMVBean map(JSONObject jsonObject) throws Exception {

                return new TradeGMVBean("", "", 0L, 1L, 0.0, jsonObject.getLong("oi_ts"));
            }
        });


        //总金额
        SingleOutputStreamOperator<TradeGMVBean> amountStream = jsonStream.map(new MapFunction<JSONObject, TradeGMVBean>() {
            @Override
            public TradeGMVBean map(JSONObject jsonObject) throws Exception {
                return new TradeGMVBean("", "", 0L, 0L, Double.parseDouble(jsonObject.getString("final_amount")), jsonObject.getLong("oi_ts"));

            }
        });
        //独立下单人数


        SingleOutputStreamOperator<TradeGMVBean> uniqueCountStream = uniqueSource.map(new MapFunction<String, TradeGMVBean>() {
            @Override
            public TradeGMVBean map(String s) throws Exception {
                JSONObject jsonObject = JSONObject.parseObject(s);
                return new TradeGMVBean("", "", 1L, 0L,0.0, jsonObject.getLong("oi_ts"));
            }
        });
        //uniqueCountStream.print("UNIQUE");
        //连接

        DataStream<TradeGMVBean> unionStream = orderCountStream.union(amountStream).union(uniqueCountStream);
        //unionStream.print("union");
        /*SingleOutputStreamOperator<TradeGMVBean> filter = unionStream.filter(new FilterFunction<TradeGMVBean>() {
            @Override
            public boolean filter(TradeGMVBean TradeGMVBean) throws Exception {
                boolean flag = false;
                if (TradeGMVBean.getTs() != null) {
                    flag = true;
                }
                return flag;
            }
        });*/
        //水位线
        //filter.print("filter---");

        //keyBy.print("keyby----------");
        SingleOutputStreamOperator<TradeGMVBean> beanWithWatermarkStream = unionStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeGMVBean>forBoundedOutOfOrderness(Duration.ofSeconds(2L)).withTimestampAssigner(new SerializableTimestampAssigner<TradeGMVBean>() {
            @Override
            public long extractTimestamp(TradeGMVBean TradeGMVBean, long l) {
                return TradeGMVBean.getTs()*1000L;
            }
        }));


        //开窗

      // beanWithWatermarkStream.print("water");

        AllWindowedStream<TradeGMVBean, TimeWindow> windowedStream = beanWithWatermarkStream.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)));

        SingleOutputStreamOperator<TradeGMVBean> reduceStream = windowedStream.reduce(new ReduceFunction<TradeGMVBean>() {
            @Override
            public TradeGMVBean reduce(TradeGMVBean value1, TradeGMVBean value2) throws Exception {
                value1.setOrderAmount(value1.getOrderAmount() + value2.getOrderCount());
                value1.setOrderCount(value1.getOrderCount() + value2.getOrderCount());
                value1.setOrderUniqueUserCount(value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount());
                System.out.println(value1.toString());
                return value1;
            }
        }, new AllWindowFunction<TradeGMVBean, TradeGMVBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow timeWindow, Iterable<TradeGMVBean> iterable, Collector<TradeGMVBean> collector) throws Exception {
                TradeGMVBean TradeGMVBean = iterable.iterator().next();
                TradeGMVBean.setStt(DateFormatUtil.toYmdHms(timeWindow.getStart()));
                TradeGMVBean.setEdt(DateFormatUtil.toYmdHms(timeWindow.getEnd()));
                TradeGMVBean.setTs(System.currentTimeMillis());
                collector.collect(TradeGMVBean);
            }
        });


        reduceStream.print("bean......");
        reduceStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_trade_total_suc_window values(?,?,?,?,?,?)"));
        env.execute(groupID);
    }
}
